package com.example.daniel.qrcodescan;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class currentPos extends Activity {

    private Button goBack=null;
    Button goal10;
    Button goal89;
    Button goal67;
    Button mButton;

    Button car;

    private EditText edtx=null;
    private EditText edty=null;
    private EditText edta=null;
    private Button confirm=null;
    int count = 0;
    private String TCP_SERVER_IP="192.168.12.195";
    private String USER_ID="1233";
    private int TCP_SERVER_PORT = 7650;
    private String lockerNumber;
    private String receivedMessage;

    public static String runTcpClient(String ip, int port, String msg) {
        try {
            {
                Socket s = new Socket(ip, port);


                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                //send output msg
                String outMsg = msg + System.getProperty("line.separator");
                out.write(outMsg);
                out.flush();
                Log.i("TcpClient", "sent: " + outMsg);

                s.close();
            }
            String inMsg = "";
            {
                Socket s = new Socket(ip, port);
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //accept server response
                String str;
                while ((str = in.readLine()) != null) {
                    inMsg += str;
                    inMsg += "\n";
                }
                inMsg += System.getProperty("line.separator");
//                Log.i("TcpClient", "received: " + inMsg);
                //close connection
                s.close();
            }
            return inMsg;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ERROR!";
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("tag","start");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("tag","resume");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        goal89 = new Button(this);
        goal89.setText("89");

        goal10 = new Button(this);
        goal10.setText("10");

        goal67 = new Button(this);
        goal67.setText("67");

        mButton = new Button(this);
        mButton.setText("CAR");

        goBack = new Button(this);
        goBack.setText("BACK");

        //set ID
        goal89.setId(2);
        goal10.setId(3);
        goal67.setId(4);
        mButton.setId(5);
        goBack.setId(6);

        float goal89w = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 490/50, getResources().getDisplayMetrics());
        float goal89h = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 500/50, getResources().getDisplayMetrics());
        float goal67w = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 400/50, getResources().getDisplayMetrics());
        float carwh = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 525/50, getResources().getDisplayMetrics());
        float distanceA = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 1835/50, getResources().getDisplayMetrics());
        float distanceB = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 8400/100, getResources().getDisplayMetrics());

        //define layout
        RelativeLayout myLayout = new RelativeLayout(this);

        //layout here
        //button 89
        RelativeLayout.LayoutParams buttonParams89 =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);

        buttonParams89.width = (int)goal89w;
        buttonParams89.height = (int)goal89h;

        buttonParams89.leftMargin=100;
        buttonParams89.topMargin=100;

        //button 10
        RelativeLayout.LayoutParams buttonParams10 =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);

        buttonParams10.width = (int)goal89w;
        buttonParams10.height = (int)goal89h;

        buttonParams10.leftMargin=(int)distanceA+100;//
        buttonParams10.addRule(RelativeLayout.ALIGN_TOP,2);

        //button 67
        RelativeLayout.LayoutParams buttonParams67 =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);

        buttonParams67.width = (int)goal67w;
        buttonParams67.height = (int)goal89h;
        buttonParams67.addRule(RelativeLayout.ALIGN_RIGHT,2);
        buttonParams67.topMargin=(int)distanceB+100;//

        //button car
        RelativeLayout.LayoutParams buttonParamsCar =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);


        buttonParamsCar.addRule(RelativeLayout.ALIGN_TOP,2);
        buttonParamsCar.addRule(RelativeLayout.ALIGN_LEFT,3);
        buttonParamsCar.width = (int)carwh;
        buttonParamsCar.height = (int)carwh;

        //button back
        RelativeLayout.LayoutParams buttonParamsBack =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);

        buttonParamsBack.leftMargin=1000;
        buttonParamsBack.topMargin=1000;
        buttonParamsBack.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
        buttonParamsBack.height = RelativeLayout.LayoutParams.WRAP_CONTENT;


        //add to view
        myLayout.addView(goal89,buttonParams89);
        myLayout.addView(goal10,buttonParams10);
        myLayout.addView(goal67,buttonParams67);
        myLayout.addView(mButton,buttonParamsCar);
        myLayout.addView(goBack,buttonParamsBack);


        //show view
        setContentView(myLayout);

        Bundle bundle = getIntent().getExtras();
        receivedMessage = bundle.getString("Server");
        final String[] Server = receivedMessage.split(" ");
        lockerNumber=Server[2];
        TCP_SERVER_PORT=Integer.parseInt(Server[1]);
        TCP_SERVER_IP=Server[0];
        USER_ID=getAndroidId(currentPos.this);

//        PosView posView = new PosView(this);
        car=(Button)findViewById(R.id.buttonCar);

        final Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {

                @Override
                public void run() {
                    count++;
                    Log.i("tag","count is"+count);
                    String command="EQRY_";
                    command=command.concat(USER_ID);
                    new CommandTask().execute(command);
                }
         }, 0, 1000);

//
//

        goBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timer.cancel();

                Intent intent = new Intent(currentPos.this, Air.class);
                Bundle bundle=new Bundle();
                bundle.putString("Server", receivedMessage);
                intent.putExtras(bundle);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                finish();
            }

        });
    }

    public class CommandTask extends AsyncTask<String, Integer, String>
    {

        float targetX = 0;
        float targetY = 0;
        float angle = 0;

        protected String doInBackground(String... msg) {
            String returnR;
            String result=msg[0];
            returnR=runTcpClient(TCP_SERVER_IP, TCP_SERVER_PORT, msg[0]);
            result=result+" "+returnR;
            return result;
        }

        protected void onPostExecute(String result) {

    //            Toast.makeText(AirAGV.this, result, Toast.LENGTH_SHORT).show();
            Log.i("TcpClient", "result: " + result);
            String[] str = result.split(" ");
            Log.i("TcpClient", "split result: " + str[0] + str[1]);
            int head=str[0].length();
            String fromCar=result.substring(head+1);

            ///////////////////////////////////////////////////////////
            String lengthX=result.substring(head+9,head+10);
            String lengthY=result.substring(head+10,head+11);
            String lengthA=result.substring(head+11,head+12);


            String targetx=result.substring(head+12,head+12+Integer.valueOf(lengthX));
            String targety=result.substring(head+12+Integer.valueOf(lengthX),head+12+Integer.valueOf(lengthX)+Integer.valueOf(lengthY));
            String targetA=result.substring(head+12+Integer.valueOf(lengthX)+Integer.valueOf(lengthY),head+12+Integer.valueOf(lengthX)+Integer.valueOf(lengthY)+Integer.valueOf(lengthA));


            Log.i("TcpClient", "received: " + fromCar);
            String firstTwochars = str[0].substring(0, 2);
            Log.i("TcpClient", "first: " + firstTwochars);
            if(firstTwochars.equals("EQ")){
                Log.i("TcpClient", "POSITION: " + fromCar);
//                showAlertDialog(fromCar);
            }

            targetX = Float.valueOf(targetx);
            targetY = Float.valueOf(targety);
            angle = Float.valueOf(targetA);


//            targetX = 0;
//            targetY = 900;
//            angle = 0;

//            targetX = 1810;
//            targetY = 900;
//            angle = 0;
//
//            targetX = 1810;
//            targetY = 7500;
//            angle = 0;

            Log.i("TcpClient", "x is " + targetX);
            Log.i("TcpClient", "y is " + targetY);
            Log.i("TcpClient", "angle is " + angle);


            float targetXX = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, targetX/50, getResources().getDisplayMetrics());
            float targetYY = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, targetY/100, getResources().getDisplayMetrics());

            Log.i("TcpClient", "x is " + targetXX);
            Log.i("TcpClient", "y is " + targetYY);

            AnimatorSet animSetXY = new AnimatorSet();
            float curTranslationX = mButton.getTranslationX();
            float curTranslationY = mButton.getTranslationY();
            float curAngle = mButton.getRotation();
            ObjectAnimator animatorX = ObjectAnimator.ofFloat(mButton, "translationX", curTranslationX, -targetXX);
            ObjectAnimator animatorY = ObjectAnimator.ofFloat(mButton, "translationY", curTranslationY, targetYY);
            ObjectAnimator animatorRotation = ObjectAnimator.ofFloat(mButton,"rotation", curAngle,angle);
            animSetXY.playTogether(animatorX,animatorY,animatorRotation);
            animSetXY.setDuration(1000);
            animSetXY.start();

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    }

    private void showAlertDialog(String message) {
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.app_name))
                .setCancelable(false)
                .setMessage(message)
                .setPositiveButton(getResources().getString(R.string.confirmBtn), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    public static String getAndroidId (Context context) {
        String ANDROID_ID = Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
        return ANDROID_ID;
    }

}
